package threadDemo;

/**
 * 线程通信
 * 使用两个线程打印1-100，线程1与线程2交替打印
 */
public class PrintNums {
    public static void main(String[] args) {
        PrintNum printNum = new PrintNum();
        //线程2
        Thread thread = new Thread(printNum);
        thread.setName("线程A");
        thread.start();

        //线程1
        Thread thread1 = new Thread(printNum);
        thread1.setName("线程B");
        thread1.start();
    }
}

class PrintNum implements Runnable {
    int num = 1;
    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                notify();//唤醒挂起的线程
                if (num <= 100) {
                    try {
                        Thread.currentThread().sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + num++);
                } else {
                    break;
                }
                try {
                    wait();// 当前线程挂起
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
